﻿using System.Globalization;
using System.Text;
using NAnt.Core;
using NAnt.Core.Attributes;
using Yahoo.Yui.Compressor;

namespace ECM7.NantContrib.Tasks.Compressor
{
	/// <summary>
	/// Минимизация файлов JavaScript
	/// </summary>
	[TaskName("minify-js")]
	public class MinifyJsTask : BaseMinifyTask<CultureInfo>
	{
		#region properties

		/// <summary>
		/// Включить детальное логирование
		/// </summary>
		[TaskAttribute("is-verbose-logging", Required = false), BooleanValidator]
		public bool IsVerboseLogging { get; set; }

		/// <summary>
		/// Выполнить обфускацию JS
		/// </summary>
		[TaskAttribute("obfuscate-js", Required = false), BooleanValidator]
		public bool ObfuscateJavaScript { get; set; }

		/// <summary>
		/// Сохранить все точки с запятой
		/// </summary>
		[TaskAttribute("preserve-all-semicolons", Required = false), BooleanValidator]
		public bool PreserveAllSemicolons { get; set; }

		/// <summary>
		/// Игнорировать eval
		/// </summary>
		[TaskAttribute("ignore-eval", Required = false), BooleanValidator]
		public bool IsEvalIgnored { get; set; }

		/// <summary>
		/// Запретить оптимизацию
		/// </summary>
		[TaskAttribute("disable-optimizations", Required = false), BooleanValidator]
		public bool DisableOptimizations { get; set; }

		/// <summary>
		/// Языковые настройки
		/// </summary>
		[TaskAttribute("thread-culture", Required = false), StringValidator]
		public string ThreadCultureString { get; set; }

		#endregion

		#region BaseMinifyTask Implementation

		/// <summary>
		/// Тип обрабатываемых файлов для отборажения в логе
		/// </summary>
		protected override string FileTypeString
		{
			get { return "JavaScript"; }
		}

		/// <summary>
		/// Сжатие файлов
		/// </summary>
		/// <param name="content">Содержание минимизируемого файла</param>
		/// <param name="cultureInfo">Специфические параметры сжатия</param>
		/// <param name="encoding">Кодировка</param>
		protected override string CompressFile(string content, CultureInfo cultureInfo, Encoding encoding)
		{
			return JavaScriptCompressor.Compress(
						content,
						IsVerboseLogging,
						ObfuscateJavaScript,
						PreserveAllSemicolons,
						DisableOptimizations,
						WithLineBreaks ? 140 : -1,
						encoding,
						cultureInfo,
						IsEvalIgnored);
		}

		#endregion

		/// <summary>
		/// Инициализация
		/// </summary>
		protected override CultureInfo GetCustomParams()
		{
			if (!string.IsNullOrEmpty(ThreadCultureString))
			{
				try
				{
					return CultureInfo.CreateSpecificCulture(ThreadCultureString);
				}
				catch
				{
					throw new BuildException("Failed to read in a legitimate culture value. ThreadCulture will not be set.", Location);
				}
			}

			return null;
		}
	}
}
